﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SiteGenerator;
internal sealed record SiteGeneratorArguments(
    DirectoryInfo Input, DirectoryInfo Output,
    bool DoOverwriting, int MinWidth, int MinHeight)
{
    public static string HelpMessage
    {
        get
        {
            var builder = new StringBuilder();
            builder.AppendLine("SiteGenerator 需要至少一个参数：");
            builder.AppendLine("[0]：图片目录");
            builder.AppendLine("[1]：输出目录（可选，默认为 output 文件夹）");
            builder.AppendLine("[2]：指示当输出目录不为空时，是否要进行覆盖（可选，默认为 false ）");
            builder.AppendLine("[3]：最小宽度（可选，默认为 100 ）");
            builder.Append("[4]：最小高度（可选，默认为 100 ）");
            return builder.ToString();
        }
    }

    private static T GetArgumentOrDefault<T>(
        string[] args, int index, T defaultValue, Func<string, T> conversion)
    {
        return args.Length >= index + 1 ? conversion(args[index]) : defaultValue;
    }

    private static T GetArgumentOrByDefaultString<T>(
        string[] args, int index, string defaultValue, Func<string, T> conversion)
    {
        return conversion(args.Length >= index + 1 ? args[index] : defaultValue);
    }

    public static bool TryParse(
        string[] args, [MaybeNullWhen(false)]out SiteGeneratorArguments result)
    {
        static DirectoryInfo CreateDirectoryInfo(string s)
        {
            return new DirectoryInfo(s);
        }

        var input = GetArgumentOrDefault(args, 0, null, CreateDirectoryInfo);
        if (input is null)
        {
            result = null;
            return false;
        }
        var output = GetArgumentOrByDefaultString(args, 1, "output", CreateDirectoryInfo);
        var doOverwriting = GetArgumentOrDefault(args, 2, false, bool.Parse);
        var minWidth = GetArgumentOrDefault(args, 3, 100, int.Parse);
        var minHeight = GetArgumentOrDefault(args, 4, 100, int.Parse);

        result = new(input, output, doOverwriting, minWidth, minHeight);
        return true;
    }
}
